package com.qi.Utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Calendar;
import java.util.Map;

/**
 * @author yd
 * @version 1.0
 * @date 2020/12/29 22:27
 */
public class JWTUtils {

    private static final String SING = "Q@#$R!";

    /**
     * 令牌的获取
     */
    public static String GetToken(Map<String, String> map) {
        //Calendar.getInstance()是获取一个Calendar对象并可以进行时间的计算，时区的指定
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.DATE, 7); // 设置过期时间 7天
        // 生成令牌
        JWTCreator.Builder builder = JWT.create();
        // payload
        map.forEach((k, v) -> {
            builder.withClaim(k, v);
        });

        String token = builder.withExpiresAt(instance.getTime())
                .sign(Algorithm.HMAC256(SING));

        //token ： eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyTmFtZSI6InhpYW9oZWkiLCJleHAiOjE2MDkyMDk2NjUsInVzZXJJZCI6MjF9.g5ETku_4AMA3fTwfgSlWrjk536Xf9ax4m5jdm-2kRhc
        return token;
    }

    /**
     * 验证token合法性
     */
    public static DecodedJWT verify(String token) {
        //创建验证对象
        return JWT.require(Algorithm.HMAC256(SING)).build().verify(token);
    }

}
